//
//  ClubFindGameViewController.swift
//  77Club
//
//  Created by Apple on 2024/8/27.
//

import UIKit
import JXSegmentedView

private let headerID    = "ClubFindGameHeaderView"

class ClubFindGameViewController: ClubBaseViewController {

    private lazy var leftTableView: UITableView = {
        let tableView = UITableView()
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = .clear
        tableView.showsVerticalScrollIndicator = false
        tableView.register(ClubFindGameLeftCell.self)
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.separatorStyle = .none
        tableView.rowHeight = 44.0.Scale
        tableView.estimatedSectionHeaderHeight = 0
        tableView.estimatedSectionFooterHeight = 0
        return tableView
    }()
    private lazy var rightTableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .plain)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = .clear
        tableView.showsVerticalScrollIndicator = false
        tableView.register(ClubFindGameBannerCell.self,ClubFindGameHandpickCell.self,ClubFindNormalCell.self,ClubFindEmptyCell.self)
        tableView.register(ClubFindGameHeaderView.self, forHeaderFooterViewReuseIdentifier: headerID)
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.separatorStyle = .none
        tableView.rowHeight = UITableView.automaticDimension
        tableView.estimatedRowHeight = 40
        tableView.estimatedSectionHeaderHeight = 0
        tableView.sectionFooterHeight = 0
        tableView.contentInset = UIEdgeInsets.zero
        tableView.sectionHeaderTopPadding = 0
        return tableView
    }()
    
    private var isNormal = false
    private var pageIndex = 1
    private var classifyArray:[ClubHomeNormalGameTypeModel] = []
    private var listModel = ClubClassifyModel()
    private var classifyId = ""
    
    private let lineView = c_make_ex(UIView.self)
        .bgColor("#88898A".toColor.alpha(0.3)).end()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        loadData()
        
        view.subviews{
            leftTableView
            lineView
            rightTableView
        }
        
        leftTableView.leading(0).top(0).bottom(0).width(92.0.Scale)
        lineView.leading(98.0.Scale).top(0).bottom(0).width(1)
        rightTableView.trailing(0).top(0).bottom(0).leading(100.0.Scale)
        rightTableView.refresh_loadMore {
            self.loadMoreData()
        }.refresh_pull {
            self.loadNewData()
        }
    }
}

//MARK: data
extension ClubFindGameViewController {
    
    private func loadData(){
        
        Task{
            let models = await network.request(.gameClassify,type: ClubHomeNormalGameTypeModel.self,isShowError: false)
            if models.isSuccess, let models = models.models, models.count > 0 {
                var temp = [ClubHomeNormalGameTypeModel]()
                temp = models
                temp[0].isSel = true
                self.classifyArray = temp
                self.classifyId = temp[0].id
                self.getGameList()
                self.leftTableView.reloadData()
            }
        }
    }
    
    private func getGameList(){
        
        Task{
            let models = await network.request(.gameList(gameType: self.classifyId, page: pageIndex),type: ClubClassifyModel.self,isShowError: false)
            rightTableView.refresh_end()
            if models.isSuccess, let model = models.model {
                self.listModel = model
                self.rightTableView.reloadData()
            }
        }
    }
    
    @objc private func loadNewData(){
        pageIndex = 1
        getGameList()
    }
    
    @objc private func loadMoreData(){
        pageIndex += 1
        Task{
            let models = await network.request(.gameList(gameType: self.classifyId, page: pageIndex),type: ClubClassifyModel.self,isShowError: false)
            rightTableView.refresh_end()
            if models.isSuccess, let model = models.model {
                if model.game.list.count > 0 {
                    for mod in model.game.list {
                        self.listModel.game.list.append(mod)
                    }
                }else{
                    rightTableView.refresh_end(true)
                }
                self.rightTableView.refresh_end(model.game.p > model.game.max_p)
            }
        }
    }
}

//MARK: - UITableViewDelegate, UITableViewDataSource
extension ClubFindGameViewController: UITableViewDelegate, UITableViewDataSource {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        if tableView == leftTableView {
            return classifyArray.count
        }else{
            if isNormal == true {
                if section == 0 {
                    if self.listModel.game.list.count == 0 {
                        return 1
                    }
                    return self.listModel.game.list.count
                } else {
                    return self.listModel.game.tuijian.count
                }
            } else {
                if section == 0 {
                    if self.listModel.slide.count > 0 {
                        return 1
                    } else {
                        return 0
                    }
                }else {
                    if self.listModel.game.list.count == 0 {
                        return 1
                    }
                    return self.listModel.game.list.count
                }
            }
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if tableView == leftTableView {
            
            let cell = tableView.dequeueReusableCell(withIdentifier: "ClubFindGameLeftCell", for: indexPath) as! ClubFindGameLeftCell
            cell.model = classifyArray[indexPath.row]
            return cell
        }else{

            let bannerCell = tableView.dequeueReusableCell(withIdentifier: "ClubFindGameBannerCell", for: indexPath) as! ClubFindGameBannerCell
            let gameCell = tableView.dequeueReusableCell(withIdentifier: "ClubFindGameHandpickCell", for: indexPath) as! ClubFindGameHandpickCell
            let normalCell = tableView.dequeueReusableCell(withIdentifier: "ClubFindNormalCell", for: indexPath) as! ClubFindNormalCell
            
            if isNormal {
                
                if indexPath.section == 0 {
                    if self.listModel.game.list.count == 0 {
                        let emptyCell = tableView.dequeueReusableCell(withIdentifier: "ClubFindEmptyCell", for: indexPath) as! ClubFindEmptyCell
                        return emptyCell
                    }else{
                        normalCell.model = listModel.game.list[indexPath.row]
                    }
//                    normalCell.model = listModel.game.list[indexPath.row]
                } else {
                    normalCell.model = listModel.game.tuijian[indexPath.row]
                }
                return normalCell
            }else{
                
                if indexPath.section == 0 {
                    bannerCell.models = listModel.slide
                    return bannerCell
                }else {
                    if self.listModel.game.list.count == 0 {
                        let emptyCell = tableView.dequeueReusableCell(withIdentifier: "ClubFindEmptyCell", for: indexPath) as! ClubFindEmptyCell
                        return emptyCell
                    }else{
                        gameCell.model = listModel.game.list[indexPath.row]
                    }
//                    gameCell.model = listModel.game.list[indexPath.row]
                    return gameCell
                }
            }
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if tableView == leftTableView {
            
            if indexPath.row == 0 {
                self.isNormal = false
            }else {
                self.isNormal = true
            }
            classifyId = classifyArray[indexPath.row].id
            loadNewData()
            var models = [ClubHomeNormalGameTypeModel]()
            classifyArray.forEach { model in
                var itemModel = model
                itemModel.isSel = false
                models.append(itemModel)
            }
            models[indexPath.row].isSel = true
            classifyArray = models
            tableView.reloadData()
        }else{

            if isNormal {
                
                var gameID = ""
                if indexPath.section == 0 {
                    gameID = listModel.game.list[indexPath.row].id
                } else {
                    gameID = listModel.game.tuijian[indexPath.row].id
                }
                let detailVC = ClubGameDetailViewController()
                detailVC.gameId = gameID
                self.navigationController?.pushViewController(detailVC, animated: true)
            }else{
                
                if indexPath.section != 0 {
                    let gameID = listModel.game.list[indexPath.row].id
                    let detailVC = ClubGameDetailViewController()
                    detailVC.gameId = gameID
                    self.navigationController?.pushViewController(detailVC, animated: true)
                }
            }
        }
        
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        
        if tableView == rightTableView {
            return 2
        }else{
            return 1
        }
    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

        if tableView == rightTableView {
            let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: headerID) as! ClubFindGameHeaderView
            header.titleString = "精选推荐"
            if isNormal == true {
                if  section == 1 && self.listModel.game.tuijian.count > 0 {
                    header.titleString = "为你推荐"
                }
            }
            return header
        }else{
            
            return nil
        }
        
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        
        if tableView == rightTableView {
            
            if isNormal == true {
                if  section == 1 && self.listModel.game.tuijian.count > 0 {
                    return 30.0.Scale
                }
                return 0
            } else {
                if section == 1 && self.listModel.game.list.count > 0{
                    return 30.0.Scale
                }else {
                    return 0
                }
            }
        }else{
            return 0
        }
    }
}

extension ClubFindGameViewController:JXSegmentedListContainerViewListDelegate {
    func listView() -> UIView {
        return view
    }
}
